﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

/**
 * 创建时间：2014/10/27 22:17:45
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace Assistant
{
    public class JSONHelper
    {
        public static T Deserialize<T>(string json)
        {
            T local = Activator.CreateInstance<T>();
            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(local.GetType());
            try
            {
                local = (T)serializer.ReadObject(stream);
            }
            catch (Exception)
            {
            }
            stream.Close();
            stream.Dispose();
            return local;
        }

        public static string Serialize<T>(T obj)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            MemoryStream stream = new MemoryStream();
            try
            {
                serializer.WriteObject(stream, obj);
            }
            catch (Exception)
            {
            }
            string str = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length);
            stream.Dispose();
            return str;
        }
    }
}
